<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminIp;
use App\Model\AdminLog;
use App\Model\OperationLogs;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class LoginController extends BaseController
{

    /**
     * 获取 登录密码串
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLoginPass(Request $request)
    {
        try {
        $password = $request->post('password', '');
        if (empty($password)) {
            throw new \Exception("The password is empty");
        }

        $pwdTmp = $password.':'.'fe154278d336d08e672745797644c364';
        $loginPass = md5($pwdTmp);

        } catch (\Exception $e) {
            return $this->toJson(self::ERROR, ['msg'=>$e->getMessage()]);
        }

        return $this->toJson(self::SUCCESS, ['loginPassMd5'=>$loginPass,'pwdTmp'=>$pwdTmp, 'password'=>$password]);
    }


    /**
     * 登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $userName = $request->post('username');
        $password = $request->post('password');
        $userName = trim($userName);
        $password = trim($password);

        $users = Users::query()->where(['name' => $userName])->first();
        if (Hash::check($password, $users['password'])) {
            $ip = client_ip();
            $adminIpModel = new AdminIp();
            $checkIp = $adminIpModel->checkIp($ip, $users['id']);
            if (!$checkIp) {
                return $this->toJson(self::LOGIN_ERROR, [], '暂未开放');
            }

            $onlyToken = $users->only('api_token');
            if ($onlyToken
                && !empty($onlyToken['api_token'])
                && (strlen($onlyToken['api_token']) > 30)
            ) {
                OperationLogs::createData($request,OperationLogs::USER, '管理员登陆');
                return $this->toJson(self::SUCCESS, $onlyToken);
            }// 密码异常，需重置密码
        }
        return $this->toJson(self::LOGIN_ERROR);
    }

    /**
     * 获取用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request)
    {
        $token = $request->header('x-token', '');
        $users = Users::where(['api_token' => $token])->first();
        $roles = $users->getAllPermissions()->pluck(['name']);
        return $this->toJson(self::SUCCESS, collect($users)->merge(['roles' => $roles, 'config' => $this->getConfig()]));
    }

    private function getConfig()
    {
        return [
            'kkaudio_api' => config('kkaudio.kkaudio_api'), 'oss_url' => config('kkaudio.oss_url')
        ];
    }

    public function list()
    {
        return $this->toJson();
    }
}
